import * as api from '../../api/api.js';
import db from '../../utils/db.js';
const app = getApp()
const os = app.os;
let scrollHeight = [0, 0];

Page({
  cacheVideoContext: [],
  data: {
    currentPage: 1, //当前页
    limit: 10, //每页数
    pageTotal: 1, //总页数
    swiperOptions: {
      circular: false,
      duration: 50,
      current: 0,
    }, // swiper 配置项
    current: 0,
    curQueue: [{
      status: 'loading'
    }], // 当前播放列表
    playInfo: [], // 播放信息，处理播放错误，进度条等信息
    isShowPlaybackRate: true, // 倍速控件
    isShowPlayBtn: false, //是否显示播放、暂停、重播按钮
    isProgressGesture: true, // 控制进度手势
    isPlayGesture: true, //是否开启播放手势（双击 播放/暂停）
    isLoading: true, //是否加载
    isFullScreen: false, // 是否全屏
    videoFitType: "cover", // 视频显示
    isPlay: false, // 是否正在播放,
    isLongPress: false, // 是否长按
  },
  onLoad: function (options) {
    os.setNavigationBarTitle({
      title: app.globalData.appName
    });
    this.getPlayletList();
  },

  onReady: function () {
    app.sendAppLogs('app', 3); // 日志
  },

  /**
   * 获取短剧列表
   */
  getPlayletList: function () {
    os.showLoading({title: '视频资源加载中...'});
    api.getPlayletList({
      is_recommend: 1,
      page: this.data.currentPage,
      limit: this.data.limit,
    }).then(res => {
      os.hideLoading({});
      let dataList = this.data.curQueue;
      let playInfo = this.data.playInfo;
      let isLoading = false;
      if (res.code == 200) {
        if(res.data.current_page == 1){
          dataList = [];
          playInfo = [];
        }
        if(res.data.list.length > 0){
          dataList = dataList.concat(res.data.list);
        }
        if(res.data.current_page < res.data.total_page && res.data.count > 0){
          isLoading = true;
        }

        if(dataList.length > 0){
          dataList.forEach((item, index) => {
            if(!item.id){
              item.id = index;
              item.episode = index;
              item.aid = item.album_id;
              if(item.list.length > 0){
                item.eid = item.list[0].episode_id;
                item.chapter_id = item.list[0].chapter_id;
                item.num = item.list[0].num;
              }
              item.preload = false;
              // item.status = "loading";
              playInfo.push({});
            }
          });
        }else{
          return this.showError();
        }
        
        this.setData({
          curQueue: dataList, 
          playInfo: playInfo,
          currentPage: parseInt(res.data.current_page), 
          pageTotal: res.data.total_page,
          isLoading: isLoading
        });

        this.preloadNextVideo();

      }else{
        this.showError();
        return app.Tips({title: res.msg});
      }
    }).catch(err => {
      os.hideLoading({});
      this.showError();
    });
  },

  /**
   * 加载数据
   */
  onloadPageData: function (){
    let currentPage = this.data.currentPage + 1;
    if (currentPage <= this.data.pageTotal){
      this.setData({currentPage: currentPage});
      this.getPlayletList();
    }
  },

  /**
   * 显示错误页面
   */
  showError(){
    this.setData({curQueue: [{
      status: 'error'
    }]});
  },

  /**
   * 切换视频表现形式
   */
  onFullscreenchange: function (e) {
    this.setData({
      videoFitType: e.detail.fullScreen ? "contain": "cover"
    });
  },

  /**
   * 获取当前播放集信息
   */
  getCurrentVideo(){
    const idx = this.data.current;
    const playInfo = this.data.playInfo;
    let currentVideo = this.data.curQueue[idx];

    if(playInfo[idx]){
      currentVideo.duration = playInfo[idx].duration || 0;
      currentVideo.currentTime = playInfo[idx].currentTime || 0;
    }

    return currentVideo;
  },

  /**
   * 发送日志
   */
  sendAppLogs(logType = 'video', markType = 1, data = {}){
    const currentVideo = this.getCurrentVideo();

    let rData = {
      method_id: currentVideo.playlet_id, 
      method_cid: currentVideo.num,
      method_amount: currentVideo.currentTime || 0
    };

    if(logType === 'video'){
      return;
      rData.method_amount = currentVideo.duration || 0;
      rData.method_mark = currentVideo.currentTime || '';

      if (markType == 2 || markType == 1) {
        rData.method_mark = currentVideo.is_unlock == 1 ? 3:1;
        rData.method_amount = currentVideo.currentTime || 0;
      }

      if (markType == 1 && rData.method_amount > 1) {
        return;
      }

      if (markType == 5 && rData.method_amount <= 1) {
        return;
      }

      if (markType == 11) {
        const currentAblum = this.data.currentAblum?.list || [];
        rData.method_mark_1 = currentAblum[currentVideo.episode + 1]?.num || '';
      }
    }

    Object.assign(rData, data);
    app.sendAppLogs(logType, markType, rData);
  },

  getMethodData(){
    const currentVideo = this.getCurrentVideo();
    return {
      method_id: currentVideo.playlet_id, 
      method_cid: currentVideo.num,
      method_amount: currentVideo.currentTime || 0
    };
  },

  /**
   * 追剧/取消追剧
   */
  bindCollect(e){
    const currentVideo = this.getCurrentVideo();
    if(currentVideo.is_collect > 0){
      os.showModal({
        content: "确定将本剧移除追剧？",
        confirmText: "取消追剧",
        cancelText: "关闭",
        confirmColor: "#f25c40",
        success(res) {
          if (res.confirm) {
            app.addAndDelCollect(currentVideo);
          }
        }
      });  
    }else{
      app.addAndDelCollect(currentVideo);
    }
  },

  /**
   * 更新追剧状态
   */
  onCollectUpdated(currentVideo, res) {
    this.updataVideoData(currentVideo.id, res);
    db.updateSeenHistoryLogs(currentVideo.playlet_id, res);
  },

  /**
   * 更新视频列表数据
   */
  updataVideoData(id, data = {}){
    let dataList = this.data.curQueue;
    let index = dataList.findIndex(obj => obj.id === id);
    if (index !== -1) {
      for(let key in data){
        dataList[index][key] = data[key];
      }
      this.setData({curQueue: dataList});
    }
  },

  /**
   * 更新播放信息
   */
  updataPlayInfo(idx, data = {}){
    let playInfo = this.data.playInfo;
    for(let key in data){
      playInfo[idx][key] = data[key];
    }
    this.setData({
      playInfo: [...playInfo],
    });
  },

  /**
   * 视频播放事件
   */
  onVideoPlay(e){
    if(e.type === 'play'){
      this.setData({isPlay: true});
      this.sendAppLogs('video', 1);
      this.sendAppLogs('video', 5);
    }
  },

  /**
   * 视频暂停事件
   */
  onVideoPause(e){
    if(e.type === "pause"){
      this.setData({isPlay: false});
      this.sendAppLogs('video', 4);
    }
  },

  /**
   * 点击视频
   */
  onVideoClick(e){
    if (!this.data.isPlay) {
      this.getVideoContext()?.play();
    } else {
      this.getVideoContext()?.pause();
    }
  },

  /**
   * 按下视频事件
   */
  onTouchStartEvent() {
    this.getVideoContext()?.playbackRate(2);
    this.setData({isLongPress: true});
  },

  /**
   * 松开视频事件
   */
  onTouchEndEvent() {
    this.getVideoContext()?.playbackRate(1);
    this.setData({isLongPress: false});
  },

  /**
   * 点击播放按钮
   */
  onPauseBtnClick(e){
    this.getVideoContext()?.play();
  },

  /**
   * 播放进度
   */
  onVideoTimeUpdate(e) {
    const { currentTime, duration } = e.detail;
    this.updataPlayInfo(e.target.dataset.episode, {
      duration: Math.floor(duration),
      currentTime: Math.floor(currentTime),
      progress: Math.floor((currentTime/duration)*100)
    });
  },

  /**
   * 缓存加载进度
   */
  onVideoProgress(e) {
    this.updataPlayInfo(e.target.dataset.episode, {
      buffered: e.detail.buffered
    });
  },

  /**
   * 进度条滑动结束事件
   */
  slideEnd(e) {
    const playInfo = e.currentTarget.dataset.info;
    const slide = e.detail.value;
    const currentTime =  parseInt((playInfo.duration / 100) * slide);
    this.getVideoContext()?.seek(currentTime);

    this.sendAppLogs('video', 10, {
      method_amount: playInfo.duration,
      method_mark: playInfo.currentTime,
      method_mark_1: currentTime
    });
  },

  /**
   * 获取资源完成后触发事件
   */
  onGetSource(e) {
    this.updataVideoData(e.currentTarget.dataset.episode, {status: "success", preload: true, cover_img: undefined});
  },
  
  /**
   * 滑动视频
   */
  swiperChange: function (e) {
    this.setData({current: e.detail.current});

    const lastIdx = e.detail.current - 1;
    if(lastIdx >= 0){
      this.getVideoContext(lastIdx)?.pause();
    }
    const nextIdx = e.detail.current + 1;
    if(nextIdx < this.data.curQueue.length){
      this.getVideoContext(nextIdx)?.pause();
    }

    this.getVideoContext()?.play();
    this.updateVideoContext()

    this.preloadNextVideo();
    if(e.detail.current == (this.data.curQueue.length - 1)){
      this.onloadPageData();
    }

    if(scrollHeight[0] !== scrollHeight[1]){
      this.sendAppLogs('app', 5, {
        method_mark: scrollHeight[0],
        method_mark_1: scrollHeight[1],
      }); // 日志
      scrollHeight[0] = scrollHeight[1];
    }
  },

  onTransition(e) {
    scrollHeight[1] = parseInt(e.detail.dy);
  },

  /**
   * 预加载下一个视频
   * @param videoInfo 
   * @returns 
   */
  preloadNextVideo() {
    if (!os.canIUse('preloadResourceVideo')) {
      return;
    }

    const current = this.data.current + 1;
    if(current > (this.data.curQueue.length - 1) || current < 0){
      return;
    }

    const videoInfo = this.data.curQueue[current];
    if(videoInfo.preload){
      return;
    }

    const that = this;
    if(app.globalData.systemInfo.platform !== "devtools"){
      os.preloadResourceVideo({
        episodeId: videoInfo.eid,
        albumId: videoInfo.aid,
        version: 1,
        cloudType: 1,
        success() {
          that.updataVideoData(videoInfo.episode, {preload: true, cover_img: undefined});
        },
      });
    } 
  },

  /**
   * 跳到下一个视频
   */
  onVideoEnded: function (e) {
    const current = this.data.current + 1;
    if(e.type === "ended"){
      if(current < this.data.curQueue.length){
        this.sendAppLogs('video', 2); 
        this.setData({current: current, 'swiperOptions.current': current});
      }
    }
  },

  /**
   * 视频出错处理
   */
  onVideoError: function (e) {
    this.updataVideoData(e.currentTarget.dataset.episode, {status: "error"});
  },

  /**
   * 跳到播放页
   */
  toVideoPage: function (e) {
    app.goPlayVideoPage(e.currentTarget.dataset.item.playlet_id, 0, 1);
  },

  /**
   * 页面显示
   */
  onShow() {
    os.disableUserScreenRecord();
    app.delayAdDialog();
  },

  /**
   * 页面隐藏
   */
  onHide() {
    os.enableUserScreenRecord();
    app.delayAdDialog(false);
  },

  /**
   * 获取当前 video context
   */
  getVideoContext(id = this.data.current) {
    // const id = this.data.current;

    if (this.cacheVideoContext[id]) {
      return this.cacheVideoContext[id];
    }

    const context = os.createVideoContext(`${id}`);
    this.cacheVideoContext[id] = context;

    return context;
  },

  /**
   * 更新视频缓存
   */
  updateVideoContext() {
    const idx = this.data.current;
    this.cacheVideoContext.forEach((item, index) => {
      if (index !== idx && index !== (idx - 1) && index !== (idx + 1)) {
        this.cacheVideoContext[index] = null;
      }
    })
  },

})